package com.example.oj_springboot.service.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 封装文件操作
 */
public class FileUtil {
    /**
     * 将filePath路径下的文件内容读出并返回
     * @param filePath
     * @return
     */
    public static String readFile(String filePath) {
        StringBuilder result = new StringBuilder();
        try (FileInputStream fileInputStream = new FileInputStream(filePath);) {
            while (true) {
                int ch = fileInputStream.read();
                if (ch == -1) {
                    break;
                }
                result.append((char)ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 将content的内容写入filePath路径下的文件
     * @param filePath
     * @param content
     */
    public static void writeFile(String filePath, String content) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}